# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: app.py
Author: kij
Create Date: 2021/2/28
-------------------------------------------------
"""
import os
import json
import socket
import optparse


# 客户端的类
class AppClient(object):
	MSG_SIZE = 1024

	def __init__(self, ip, port):
		self.ip = ip
		self.port = port
		self.user_name = None
		self.user_password = None
		self.make_connection()
		self.current_dir = None

	def make_connection(self):
		"""链接"""
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.connect((self.ip, self.port))

	def auth(self, user_name, user_password):
		"""用户认证"""
		# 发送数据
		self.send_msg('auth', username=user_name, password=user_password)
		# 接收服务器数据
		return self.get_response()

	def interactive(self):
		"""处理所有ftpsercer交互"""
		print("密码正确开始处理")

	def send_msg(self, action_type, **kwargs):
		"""发送数据"""
		msg_data = {
			'action_type': action_type,
			'fill': '',
		}
		msg_data.update(kwargs)
		bytes_msg = json.dumps(msg_data).encode('utf-8')
		if self.MSG_SIZE > len(msg_data):
			msg_data['fill'] = msg_data['fill'].zfill(self.MSG_SIZE - len(bytes_msg))
			bytes_msg = json.dumps(msg_data).encode('utf-8')
		self.sock.send(bytes_msg)

	def get_response(self):
		"""获取服务器信息"""
		data = self.sock.recv(self.MSG_SIZE)
		return json.loads(data.decode('utf-8'))

	def _get(self, action_type, file_name):
		"""下载文件"""
		# 发送请求数据
		self.send_msg(action_type, filename=file_name)
		# 接收数据
		return self.get_response()

	def get_file(self, file_name, response):
		file_size = response.get('file_size')
		received_size = 0
		# save to shelve db

		file_abs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)
		print(file_abs_path)

		f = open(file_abs_path,mode='wb')
		while received_size < file_size:
			if file_size - received_size < 8192:
				data = self.sock.recv(file_size - received_size)
			else:
				data = self.sock.recv(8192)
			received_size += len(data)
			f.write(data)
		f.close()
		return True, '文件下载完成'


	def _ls(self,action_type):
		'''显示文件夹'''
		# 发送查看文件路径命令
		self.send_msg(action_type)
		# 接收数据
		return self.get_response()
	def get_folder(self,cmd_result_size):
		"""文件夹目录"""
		received_size = 0
		cmd_result = b''
		while received_size < cmd_result_size:
			if cmd_result_size - received_size < 8192:
				data = self.sock.recv(cmd_result_size - received_size)
			else:
				data = self.sock.recv(8192)
			cmd_result += data
			received_size += len(data)
		else:
			return cmd_result.decode("utf-8")

